<template>
    <div class="search-line">
        <el-form v-model="search" inline>
            <el-form-item label="角色名" prop="role_name">
                <el-input v-model="search.role_name" placeholder="请输入角色名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchList">
                    <i class="iconfont icon-sousuo"></i>
                    搜索
                </el-button>
                <el-button @click="searchReset">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="user-tab">
        <div class="opBtn">
            <el-button type="danger" size="default" @click="delGroup">
                <i class="iconfont icon-shanchu"></i>
                批量删除
            </el-button>
            <el-button type="primary" size="default" @click="add">
                <i style="font-size: 26px;">+</i>
                添加
            </el-button>
        </div>

        <el-table :data="list" style="width: 100%;" height="460" border ref="multipleTableRef">
            <el-table-column type="selection" align="center">
            </el-table-column>

            <el-table-column align="center" label="角色编号" prop="role_id" width="120" />
            <el-table-column align="center" prop="role_name" label="角色名称" width="200" />
            <el-table-column align="center" prop="role_desc" label="角色描述" width="200" />
            <el-table-column align="center" prop="created_at" label="创建于" width="200" />
            <el-table-column align="center" prop="updated_at" label="更新于" width="200" />
            <el-table-column align="center" fixed="right" label="操作" width="240">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="editRow(scope.$index)">
                        <i class="iconfont icon-bianji"></i>
                    </el-button>
                    <el-button type="success" size="small" @click="editRole(scope.$index)">
                        分配权限
                    </el-button>
                    <el-button type="danger" size="small" @click.prevent="deleteRow(scope.$index)">
                        <i class="iconfont icon-shanchu"></i>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
    <el-dialog v-model="dialogVisible" title="角色编辑" :width="srceenWidth" :before-close="handleClose">
        <el-form :model="form" label-width="120px">
            <el-form-item label="角色名称" prop="role_name" required>
                <el-input v-model="form.role_name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="role_desc">
                <el-input v-model="form.role_desc" placeholder="请输入角色描述" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即编辑</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-drawer v-model="dialogVisible1" title="权限分配" :before-close="handleClose" size="50%">
        <el-form :model="form1" label-width="120px">
            <el-form-item label="角色名称" prop="role_name">
                <el-input v-model="form1.role_name" placeholder="请输入角色名称" disabled />
            </el-form-item>
            <el-form-item>
                <el-tree ref="treeRef" :data="form1.menu" current-node-key show-checkbox node-key="auth_id"
                    :props="defaultProps" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="upQx">
                    立即创建
                </el-button>
                <el-button @click="dialogVisible1 = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>


<script setup>
import { onMounted, ref, reactive, nextTick } from 'vue'
import { requestIns } from '@/utils/request'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const list = ref([])
const search = ref({
    role_name: '',
})
const srceenWidth = ref('50%')
onMounted(() => {
    getList()
    changeWidth()
    getMenu()
})
window.addEventListener('resize', () => {
    changeWidth()
})

const treeRef = ref(null)

const getMenu = async () => {
    const res = await requestIns.request('/auth/menu')
    if (res.state == 200) {
        form1.menu = res.data
    } else {
        ElMessage.error(res.message)
    }
}
const upQx = async () => {
    console.log(editId.value)
    console.log(treeRef.value.getCheckedKeys(true).join(','))
    console.log(treeRef.value.getCheckedKeys().join(','))
    const res = await requestIns.request('/role/assign', 'put', {
        role_id: editId.value,
        auth_ids: treeRef.value.getCheckedKeys().join(','),
        auth_ids_son: treeRef.value.getCheckedKeys(true).join(',')
    })
    console.log('res:' + JSON.stringify(res))


}
const defaultProps = {
    children: 'children',
    label: 'auth_name',
}
const changeWidth = () => {
    if (window.innerWidth < 1000) {
        srceenWidth.value = '90%'
    } else {
        srceenWidth.value = '50%'
    }
}
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const router = useRouter()
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const form = reactive({
    role_name: '',
    role_desc: ''
})
const form1 = reactive({
    role_name: '',
    menu: []
})
const getList = async () => {
    const res = await requestIns.request('/role/index', 'get', {
        pagenum: currentPage.value,
        pagesize: pageSize.value,
        ...search.value
    })
    console.log(res)
    if (res.state = 200) {
        list.value = res.list
        total.value = res.total
    }
}

const handleClose = (done) => {
    done()
}
const deleteRow = async (index) => {
    const item = list.value.find((item, idx) => idx == index)
    console.log(item.role_id)

    const res = await requestIns.request('/role/delete', 'delete', {
        role_id: item.role_id
    })
    console.log(res)
    if (res.state === 200) {
        getList()
        ElMessage.success('删除成功')
    }
}
const add = () => {
    router.push('/role/create')
}
const multipleTableRef = ref([])
const delGroup = async () => {
    const ids = multipleTableRef.value.getSelectionRows().map(item => item.role_id)
    const res = await requestIns.request('/role/delete', 'delete', {
        role_id: ids.join(',')
    })
    console.log(res)
    if (res.state === 200) {
        getList()
        ElMessage.success('删除成功')
    }

}
const editId = ref(-1)
const editRow = (index) => {
    dialogVisible.value = true
    editId.value = list.value[index].role_id
    form.role_name = list.value[index].role_name
    form.role_desc = list.value[index].role_desc
}
const editRole = (index) => {
    dialogVisible1.value = true
    form1.username = list.value[index].username
    form1.role_name = list.value[index].role_name
    editId.value = list.value[index].role_id
    nextTick(() => {
        list.value.forEach(item => {
            if (item.role_id == editId.value) {
                treeRef.value.setCheckedKeys(item.auth_ids_son.split(','), false)
            }
        })
    })

}

const onSubmit = async () => {
    const res = await requestIns.request('/role/update', 'put', {
        role_id: editId.value,
        ...form
    })
    console.log(res)
    if (res.state === 200) {
        ElMessage.success(res.msg)
    } else {
        ElMessage.error(res.msg)
    }
    reset()
    dialogVisible.value = false
    getList()
}
const reset = () => {
    form.username = ''
    form.password = ''
    form.mobile = ''
    form.avatar = ''
}
const handleSizeChange = (val) => {
    currentPage.value = 1
    pageSize.value = val
    getList()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getList()
}
const searchList = () => {
    getList()
}
const searchReset = () => {
    search.value.username = ''
    search.value.mobile = ''
    search.value.role_name = ''
    search.value.created_at = ''
    search.value.updated_at = ''
}
</script>

<style lang="scss" scoped>
.user-tab {
    background-color: #fff;
    padding: 15px;

    .opBtn {
        margin-bottom: 15px;
    }
}

.demo-pagination-block {
    margin-top: 10px;
    width: 100%;
    display: flex;
    justify-content: center;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.search-line {
    background-color: #fff;
    padding: 15px 0 0 15px;
    box-sizing: border-box;
    margin-bottom: 20px;
}

.switch-btn {
    margin-left: 15px;

    &:hover {
        color: #409eff;
        cursor: pointer;
    }
}
</style>